import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:sweetim/model/simple_message.dart';
import 'package:sweetim/service/api_service.dart';
import 'package:sweetim/service/member_service.dart';
import 'package:sweetim/service/socket_service.dart';

import '../const/const.dart';

class ChatController extends GetxController {
  final String fid;

  ChatController(this.fid);

  final SocketService _socketService = Get.find();
  final MemberService _memberService = Get.find();
  final ApiService _apiService = Get.find();
  final textController = TextEditingController();

  final msgList = <SimpleMessage>[].obs;
  var loading = false.obs;

  var loadMoreFlag = true.obs;

  final ScrollController scrollController =
      ScrollController(keepScrollOffset: true);

  int _start = 0;

  @override
  void onInit() async {
    super.onInit();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        Get.log("加载更多 ${_start}");
        _loadMoreMsg(_start);
        _start += 10;
      }
    });
    _socketService.addListen((msg) {
      msgList.insert(0, SimpleMessage.fromJson(msg));
    });
    _initQueryMessage();
  }

  void sendMsg0(msg) {
    _socketService.sendMsg(msg);
  }

  void sendMsg(String fid) {
    //  // 接受人
    //       Long rid = body.getLong("rid");
    //       // 发送人
    //       Long sid = body.getLong("sid");
    //       String content = body.getString("content");
    var content = textController.text;
    var msg = {"rid": fid, "content": content};
    sendMsg0(msg);
    msgList.insert(
        0,
        SimpleMessage(
            id: count.toString(),
            rid: fid,
            sid: _memberService.id,
            content: content,
            time: 1));
    count++;
    textController.clear();
  }

  var count = 0;

  String name() {
    return _memberService.getInfo().m?.name ?? "";
  }

  void _loadMoreMsg(int start, {int length = 10}) async {
    loading.value = true;
    var resp = await _apiService.get0(
        queryChatMessageListUrl + "?start=${start}&fid=${fid}&length=${length}",
        _memberService.token);
    if (resp != null) {
      List<dynamic> list = resp["list"];
      if (list.isNotEmpty) {
        msgList.addAll(list.map((e) => SimpleMessage.fromJson(e)).toList());
      } else {
        loadMoreFlag.value = false;
      }
    }
    loading.value = false;
  }

  void _initQueryMessage() {
    _loadMoreMsg(0, length: 20);
    _start += 20;
  }
}
